import django
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'public.settings')
django.setup()

from apps.wechat.models import Wechat
from apps.vip.models import Vip, VipOrder
from apps.coupon.utils import make_member_coupons
from datetime import datetime
from dateutil.relativedelta import relativedelta

# 每天凌晨0点后点执行，检测符合条件的会员发放会员券
for user in Wechat.objects.filter(is_member=True):
    today = datetime.now()
    # 更新会员状态
    if user.member_expired < today:
        user.is_member = False
        user.member_expired = None
        user.member_started = None
        user.member_counter = 0
        user.save()
        continue

    # 计算时间发放会员券
    user.member_counter += 1
    except_date = user.member_started + relativedelta(months=user.member_counter)
    if except_date < today:
        make_member_coupons(user)
        user.save()

# 每天凌晨0点后点执行，检测符合条件会员卡触发生成服务订单
for vip in Vip.objects.filter(status='1', surplus_times__gt=0):
    today = datetime.now()
    weeks = vip.service_counter * int(vip.unit)
    except_date = vip.service_started + relativedelta(weeks=weeks)
    # 提前一天创建服务订单
    diff_date = except_date - relativedelta(days=2)
    if diff_date < today:
        VipOrder.objects.create(
            vip=vip,
            ayi_id=vip.ayi_id,
            sku_name='健康保洁',
            sku_unit='4小时',
            contacts=vip.name,
            mobile=vip.mobile,
            service_addr=vip.address,
            service_date=except_date.strftime('%Y-%m-%d %H:%M'),
        )
        vip.service_counter += 1
        vip.surplus_times -= 1
        vip.save()
